<?php


namespace XinYaTable\Forms\Exceptions;

use Throwable;

class BaseException extends \Exception
{
    private $_code;
    private $_replaceParam;

    protected $defaultMsg
        = [
            'msg' => '这个api找不到了,别担心!我们已经派出最牛的人在修复...'
        ];

    /**
     * @var array 对应模块的Code
     *   包含动态内容的错误Msg 对{$XXX} 为可替换文本
     *   601 => [ 'msg' => '{$title}: 你好, {$body}验证码已经失效！' ]
     */
    protected $exceptionMessage = [];
    private $_defaultCodeMessages = [
            400 => ['msg' => "请求参数有误。"],
            401 => ['msg' => "授权Token错误。"],
            403 => ['msg' => "服务器拒绝执行。"],
            404 => ['msg' => "请求方法不存在。"],
            405 => ['msg' => "禁止操作。"],
            407 => ['msg' => "没有权限。"],
            415 => ['msg' => "请求类型错误。"],
            408 => ['msg' => "请求超时。"],
            500 => ['msg' => "网络异常"],
            501 => ['msg' => "服务器不支持当前请求所需要的某个功能。"],
        ];

    public function __construct(int $code, array $replaceParam = [], Throwable $previous = null)
    {
        $this->_code            = $code;
        $this->_replaceParam    = $replaceParam;
        $this->exceptionMessage += $this->_defaultCodeMessages;
        $message                = $this->getExceptionMessage();
        parent::__construct($message, $code, $previous);
    }

    public function getExceptionMessage()
    {
        $codeMessage = $this->_getCodeMessage($this->_code);
        if (empty($this->_replaceParam)) {
            return $codeMessage;
        }
        $replaceKeys = array_keys($this->_replaceParam);
        foreach ($replaceKeys as &$key) {
            $key = '{$' . $key . '}';
        }

        return str_replace($replaceKeys, $this->_replaceParam, $codeMessage);
    }

    private function _getCodeMessage(int $code)
    {
        return ($this->exceptionMessage[$code] ?? [])['msg'] ?? $this->defaultMsg['msg'];
    }
}